package com.hunlian.makelove.activity;

import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.R;
import com.hunlian.makelove.bean.UpdateBean;
import com.hunlian.makelove.common.ActivityMgr;
import com.hunlian.makelove.common.AppConfig;
import com.hunlian.makelove.common.NetworkConnectChangedReceiver;
import com.hunlian.makelove.fragment.MineFrag;
import com.hunlian.makelove.fragment.OppositeSexFrag;
import com.hunlian.makelove.fragment.ReceiveInvitingFrag;
import com.hunlian.makelove.fragment.SendInvitingFrag;
import com.hunlian.makelove.net.NetVisitCallback;
import com.hunlian.makelove.net.api.UpdataServiceVisit;
import com.hunlian.makelove.tools.ACache;
import com.hunlian.makelove.tools.DisplayUtil;
import com.hunlian.makelove.tools.LogTools;
import com.hunlian.makelove.tools.MyToast;
import com.hunlian.makelove.update.AppUpdate;
import com.hunlian.makelove.update.Update;
import com.hunlian.makelove.widget.address.AppManager;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

public class MainActivity extends FragmentActivity {
	private FragmentTabHost mTabHost;
	private MainActivity mSelf;
	private int[] mImageViewArray = { R.drawable.selector_tab_opposite,
			R.drawable.selector_tab_invited, R.drawable.selector_tab_send,
			R.drawable.selector_tab_mine };
	private Class[] fragmentArray = { OppositeSexFrag.class,ReceiveInvitingFrag.class,
			SendInvitingFrag.class, MineFrag.class };
	private String[] mTextviewArray = { "缘分","邀请我", "我邀请","我的"};

	private ImageLoader mImageLoader;
	private Update update = null;

	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		ActivityMgr.getActivityMgr().clear();
		ActivityMgr.getActivityMgr().add(this);
		setContentView(R.layout.act_main);
		mSelf = this;

		getImageLoader();

		initView();
		ifUpdataVersions();

		//获取屏幕宽高
		DisplayMetrics dm = DisplayUtil.getDisplayMetrics(this);
		AppConfig.SCREEN_WIDTH = dm.widthPixels;
		AppConfig.SCREEN_HEIGHT = dm.heightPixels;

		//监听wifi
		NetworkConnectChangedReceiver networkConnectChangedReceiver = new NetworkConnectChangedReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
		filter.addAction("android.net.wifi.STATE_CHANGE");
		registerReceiver(networkConnectChangedReceiver,filter);
	}
	
	
	@Override
	protected void onDestroy() {
		if(update!=null){
			update.destroy();
			update = null;
		}

		super.onDestroy();
	}

	private void initView() {
		mTabHost = (FragmentTabHost) findViewById(R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.content);
		mTabHost.getTabWidget().setDividerDrawable(null);
		int count = fragmentArray.length;
		TabHost.TabSpec tabSpec;
		for (int i = 0; i < count; i++) {

			tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(
					getTabView(i));
			mTabHost.addTab(tabSpec, fragmentArray[i], null);
		}

	}

	/**
	 * 给Tab按钮设置图标和文字
	 */
	private View getTabView(int index) {
		View view = LayoutInflater.from(this).inflate(R.layout.main_tab_item,
				null);

		ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
		imageView.setImageResource(mImageViewArray[index]);

		TextView textView = (TextView) view.findViewById(R.id.textview);
		textView.setText(mTextviewArray[index]);

		return view;
	}


	private long mExitTime;

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (event.getKeyCode()) {
			case KeyEvent.KEYCODE_BACK:
				
					if ((System.currentTimeMillis() - mExitTime) > 2000) {
						Toast.makeText(MainActivity.this, "再按一次退出婚恋网",
								Toast.LENGTH_SHORT).show();
						mExitTime = System.currentTimeMillis();
					} else {
						clear();
						AppManager.getAppManager().finishAllActivity();
						MainActivity.this.finish();
					}
					return true;
				
			}
		}

		return super.dispatchKeyEvent(event);
	}

	private void getImageLoader() {
		mImageLoader = ImageLoader.getInstance();
		File cacheDir = StorageUtils.getOwnCacheDirectory(MainActivity.this,
				"hunlian/Cache");
		ImageLoaderConfiguration imageLoaderConfig = new ImageLoaderConfiguration.Builder(
				MainActivity.this).memoryCacheExtraOptions(480, 800)
				.threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
				.memoryCacheSize(2 * 1024 * 1024)
				.discCacheSize(50 * 1024 * 1024)
				.discCache(new UnlimitedDiscCache(cacheDir)).writeDebugLogs()
				.build();
		mImageLoader.init(imageLoaderConfig);

	}


	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);

	}

	@Override
	protected void onPause() {
		super.onPause();
		TCAgent.onPause(this);
		MobclickAgent.onPause(this);
	}


	/**
	 * 检查是否有新版本
	 */
	private void ifUpdataVersions() {
		try {
			if (!AppApplication.networkAvailable) {
				MyToast.showShort("没有网络");
				return;
			}

			String pkName = this.getPackageName();
			int versionCode = this.getPackageManager()
					.getPackageInfo(pkName, 0).versionCode;

			UpdataServiceVisit visit = new UpdataServiceVisit(MainActivity.this);
			visit.setParamters(pkName, versionCode + "");
			visit.getResult(new NetVisitCallback<UpdateBean,Object>(mSelf) {

				@Override
				public void onSuccess(UpdateBean bean) {
	
					String needToUpdate = bean.getNeedToUpdate();
					if (!needToUpdate.equals("0")) {
						AppUpdate updateBean = new AppUpdate();
						updateBean.setType(needToUpdate);
						updateBean.setLog(bean.getChangeLog());
						updateBean.setDownloadUrl(bean.getDownloadUrl());
						updateBean.setVersion(bean.getVersionName());
						
						update = new Update();
						update.checkUpdate(MainActivity.this);
						update.setUpdate(updateBean);
						// 弹出更新的对话框
						update.showUpdateDialog();
					}
				}

				@Override
				public void onFailure(String errCode, String errMessage,Object obj) {
					LogTools.i("版本更新反馈数据：" + errMessage);
					if(errMessage.equals("请从官方网站(konly.cn)下载最新版本重新安装")){
						MyToast.showShort(errMessage);
						MainActivity.this.finish();
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private void clear(){
		ACache.get(AppApplication.getAppContext()).remove("ArrayList<ContactModel>");
	}
}

